package com.hc.controller;

import com.hc.common.bean.Result;
import com.hc.common.bean.ResultUtil;
import com.hc.jwt.JwtUtil;
import com.hc.security.UserDetailsServiceImpl;
import com.hc.vo.UserVO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author hc
 * @date 2022/1/11 15:28
 */
@RestController
public class UserController {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserDetailsServiceImpl userDetailsService;

    @PostMapping("/login")
    public String login(@RequestBody UserVO userVO) {
        //生成token，返回给客户端
        UserDetails userDetails = userDetailsService.loadUserByUsername(userVO.getUsername());

        String token = jwtUtil.generateToken(userDetails);
        return token;
    }

    @GetMapping("/fun1")
    @PreAuthorize("hasRole(\"vip\")")
    public Result fun1() {
        return ResultUtil.success("fun1");
    }

    @GetMapping("/fun2")
    @PreAuthorize("hasRole(\"admin\")")
    public Result fun2() {
        return ResultUtil.success("fun1");
    }

    @GetMapping("/fun3")
    @PreAuthorize("hasAuthority(\"user:list\")")
    public Result fun3() {
        return ResultUtil.success("fun1");
    }

    @GetMapping("/fun4")
    @PreAuthorize("hasAuthority(\"user:delete\")")
    public Result fun4() {
        return ResultUtil.success("fun1");
    }

}
